<template>
	<view>
		<view class="write_title">
			<input type="text" v-model="title" placeholder="请输入标题"></input>
		</view>
		<!-- 内容展示区 -->
		<view class="artList">
			<block v-for="(item,index) in artList" :key="index">
				<view class="item" v-if="item.type == 'image'">
					<image :src="item.content" :data-index="index" mode="widthFix" @tap="removeImg" />
				</view>
				<view class="item" v-if="item.type == 'text'">
					<textarea value="item.content" placeholder="" v-model="artList[index].content" />
					<view :data-index="index" class="deleteText" @tap="deleteText">删除</view>
				</view>
			</block>
		</view>
		
		<!-- 输入区 -->
		<form @submit="submit">
			<view class="inputArea">
				<view class="addImg" @tap="addImg">+图片</view>
				<view class="addText">
					<textarea name="artText" maxlength="-1" v-model="inputContent" placeholder="请输入文本"/>
					<button type="primary" form-type="submit">添加</button>
				</view>
			</view>
		</form>
		
		<!-- 选择分类 -->
		<view class="art-cate">
			<view>文章分类</view>
			<view class="">
				<picker mode="selector" :range="caties" @change="cateChange">
					<view>{{caties[currentCateIndex]}}</view>
				</picker>
			</view>
		</view>
		
		<!-- 提交按钮 -->
		<view class="submitNow" v-if="artList.length > 0" @tap="submitNow">发布文章</view>
	</view>
</template>

<script>
	var loginRes, _self;
	var signModel = require('../../commons/sign.js');
	export default {
		data() {
			return {
				title: '',   //记录用户输入的标题，不论用户输入的变化还是变量的变化，input区域的值都会发生变化  4
				artList: [],  //文章的核心内容区域   8
				inputContent: "",   //客户添加文本的一个双向绑定  24
				needUploadImg: [],  //统计客户上传的图片放在这个数组进行保存
				uploadIndex: 0,    //记录上传到哪个图片
				//分类
				caties: ['点击选择'],
				currentCateIndex: 0,
				catiesFromApi: [],   //记录真实选择的api接口数据的分类id
				sedCateIndex: 0   
			}
		},
		onLoad: function() {
			_self = this;
			//登录检查函数
			loginRes = this.checkLogin('../write/write', 2);   
			if(!loginRes){return false;};
			//签名
			signModel.sign(_self.apiServer);
			
			//加载文章的分类
			uni.request({
				url: this.apiServer+'category&m=index',
				method: 'GET',
				success: res => {
					if(res.data.status == 'ok'){
						// 把数据格式整理为 picker 支持的格式 ['分类名', ...]
						var categories = res.data.data;
						for(var k in categories){
							_self.caties.push(categories[k]);
						}
						// 记录分类信息
						_self.catiesFromApi = categories;
					}
				}
			});
		},
		methods: {
			submitNow: function() {
				if(this.title.length < 2){  //如果标题的长度 < 2
					uni.showToast({   //显示消息提示框
						title: '请输入标题',  //提示内容
						icon: "none",  //图标
					}); 
					return ;
				}
				if(this.artList.length < 1){uni.showToast({title: '请填写文章的内容', icon: "none"}); return ;}
				if(this.sedCateIndex < 1){uni.showToast({title: '请选择分类', icon: "none"}); return ;}
				//上传图片  一次一个多次上传 【递归函数】
				//上传完成后整体提交数据
				//首先整理一下需要上传的图片
				//this.needUploadImg = [{tmpurl: 临时地址, index: 数据索引}]
				this.needUploadImg = [];
				for(var i = 0; i < this.artList.length; i++){  //对artList(保存上传的图片)进行循环  
					if(this.artList[i].type == 'image'){  //如果artList[i]的type为image，就认为是需要上传的
						//把上传的数据保存到needUploadImg，用push方式向数组内压入一个对象，对象为图片的临时地址和indexID
						this.needUploadImg.push({"tmpurl": this.artList[i].content, "indexID": i});
					}
				}
				console.log(this.needUploadImg);
				this.uploadImg();
			},
			uploadImg: function() {
				if(this.needUploadImg.length < 1 || this.uploadIndex >= this.needUploadImg.length){
					//文章提交
					uni.showLoading({title: '正在提交'});
					var sign = uni.getStorageSync('sign');
					uni.request({
						url: this.apiServer + 'art&m=add',
						method: 'POST',
						header: {'content-type': "application/x-www-form-urlencoded"},
						data: {
							title: _self.title,
							content: JSON.stringify(_self.artList),
							uid: loginRes[0],
							random: loginRes[1],
							cate: _self.sedCateIndex,
							sign: sign
						},
						success: function(res) {
							// console.log(res);
							if(res.data.status == 'ok') {
								uni.showToast({title: "提交成功", icon: "none"});
								_self.artList = [],   //清空页面上所有数据
								signModel.sign(_self.apiServer);  //重新的签名
								//防止数据缓存   所有页面上的数据都赋值成初始化
								_self.currentCateIndex = 0;
								_self.sedCateIndex = 0;
								_self.needUploadImg = 0;
								_self.title = '';
								setTimeout(function(){
									uni.switchTab({
										url: '../my/my'
									})
								}, 1000);
							}else {
								uni.showToast({title: res.data.data, icon: "none"});
							}
						}
					});
					
				}else{
					//图片上传
					uni.showLoading({title: "上传图片"});   //显示loading提示框
					var uploader = uni.uploadFile({   //uni.uploadFile将本地资源上传到开发者服务器
						url: _self.apiServer+ 'uploadImg&m=index',   //要上传的服务器地址
						filePath: _self.needUploadImg[_self.uploadIndex].tmpurl,
						name: 'file',
						success: (uploadFileRes) => {
							uploadFileRes = JSON.parse(uploadFileRes.data);  //通过 JSON.parse()解析数据，这些数据会成为 JavaScript 对象
							if(uploadFileRes.status != 'ok'){   //如果没有上传成功
								console.log(uploadFileRes);   //告诉用户上传失败，终止运行
								uni.showToast({title: "上传图片失败，请重试！", icon: "none"});
								return false;
							}
							//将已经上传的文件地址赋值给文章数据
							var index = _self.needUploadImg[_self.uploadIndex].indexID;
							_self.artList[index].content = _self.staticServer + uploadFileRes.data;
							console.log(_self.artList);
							// console.log('成功');
							_self.uploadIndex ++;
							//递归上传
							setTimeout(function(){_self.uploadImg();},1000);
							
						},
						fail: () => {
							uni.showToast({title:"上传图片失败,请重试!", icon:"none"});
						}
					});
					uni.hideLoading();
					
				}
			},
			submit: function(res){
				var content = res.detail.value.artText;
				if(content.lenth < 1) {
					uni.showToast({
						title: "请输入内容",
						icon: 'none'
					});
					return ;
				}
				this.artList.push({"type": "text", "content": content});
				this.inputContent = '';
			},
			deleteText: function(e){
				var  index = e.currentTarget.dataset.index;
				uni.showModal({
					content: "确定要删除吗",
					title: '提示',
					success: (e) => {
						_self.artList.splice(index, 1);
					}
				})
			},
			removeImg: function(e){
				var index = e.currentTarget.dataset.index;
				uni.showModal({
					content: "确定要删除此图片吗",
					title: '提示',
					success: (e) => {
						if(e.confirm) {
							_self.artList.splice(index, 1);  //splice方法 删除数组内指定index的数据
						}
					}
				})
			},
			addImg: function(){
				uni.chooseImage({   //从本地相册选择图片或使用相机拍照
					count: 1,   //最多可以选择的照片，默认9
					sizeType: ['compressed'],   //压缩图
					success: function(res){
						//把选择好的图片临时地址，压缩到artList这个数组，格式为对象格式
						_self.artList.push({"type": "image","content": res.tempFilePaths[0]}) 
					}
				})
			},
			cateChange: function (e) {
				var sedIndex = e.detail.value;
				this.currentCateIndex = sedIndex;
				//获取选择的分类名称
				if(sedIndex < 1){return ;}
				var cateName = this.caties[sedIndex];
				for(var k in this.catiesFromApi) {
					if(cateName == this.catiesFromApi [k]){
						this.sedCateIndex = k;
						break;
					}
				}
				this.currentCateIndex = sedIndex;
			}
		}
	}
</script>

<style>

</style>
